package com.laihui.activity;

import android.app.Activity;
import android.graphics.Color;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.bigkoo.pickerview.OptionsPickerView;
import com.google.gson.Gson;
import com.laihui.MyApplication;
import com.laihui.base.BaseActivity;
import com.laihui.entity.BankBean;
import com.laihui.entity.BankList;
import com.laihui.entity.JsonBean;
import com.laihui.entity.RetMap;
import com.laihui.utils.BankcardCheckUtils;
import com.laihui.utils.JsonFileReader;
import com.laihui.utils.ToastUtil;
import com.laihui.view.TopBar;

import org.json.JSONArray;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;

import butterknife.BindView;
import butterknife.OnClick;
import rx.Subscriber;
import rx.android.schedulers.AndroidSchedulers;
import rx.schedulers.Schedulers;

public class BindCardActivity extends BaseActivity {


    @BindView(R.id.tv_choose_bank)//选择银行--textview
            TextView tvChooseBank;
    @BindView(R.id.tv_address)//选择银行--textview
            TextView mTvAddress;



    private ArrayList<JsonBean> options1Items = new ArrayList<>();
    private ArrayList<ArrayList<String>> options2Items = new ArrayList<>();
    private ArrayList<ArrayList<ArrayList<String>>> options3Items = new ArrayList<>();


    ArrayList<BankBean> bankOptionItems = new ArrayList<>();



    @BindView(R.id.topbar)//topbar
            TopBar topbar;

    @BindView(R.id.ll_choose_bank)//选择银行--LinearLayout
            LinearLayout llChooseBank;
    @BindView(R.id.et_bank_number)//银行卡号输入框
            EditText etBankNumber;

    @BindView(R.id.btn_submit)//审核按钮
            Button btnSubmit;

     @BindView(R.id.et_branch)
    EditText etBranch;

    private static final String TAG = "BindCardActivity";
    private int isSend = 0 ;
    private Activity mActivity;
    private MyApplication application;
//    private ArrayList<Integer> bankIdList = new ArrayList<>();//银行id集合
//    private ArrayList<String> bankNameList = new ArrayList<>();//银行英文名称集合
//    private ArrayList<String> bankValueList = new ArrayList<>();//银行中文名称集合
//    private ArrayList<BankCard.BanklistsBean> bankCardList = new ArrayList<>();//银行卡列表集合

    private String bankId = "";//选中银行卡id
    private String bankName = "";//选中银行卡英文名称


    private String provinceNID = "";//选中省份id
    private String cityNID = "";//选中城市id
    private String countryNID = "";//选中区域id


    @Override
    public void init() {
        mActivity = BindCardActivity.this;
        application = (MyApplication) getApplication();

        topbar.setOnTopbarClickListener(new TopBar.topbarClickListener() {
            @Override
            public void leftClick() {
                finish();
            }

            @Override
            public void rightClick() {

            }
        });
        getBankCard();
        setListener();
        initJsonData();
    }

    /**
     * 绑定银行卡
     */
    private void bindCard() {
        String branch = etBranch.getText().toString();
        //  String password = etPassword.getText().toString();
        String bankCard = etBankNumber.getText().toString();
        String address = mTvAddress.getText().toString();


        if (bankId.equals("")) {
            ToastUtil.showToast(mActivity, "请选择银行");
            return;
        }
       if (branch.isEmpty()) {
            ToastUtil.showToast(mActivity, "请输入开户地");
            return;
        }
//        if (password.isEmpty()) {
//            ToastUtil.showToast(mActivity, "请输入交易密码");
//            return;
//        }
        if (bankCard.isEmpty()) {
            ToastUtil.showToast(mActivity, "请输入银行卡号");
            return;
        }

        if (!BankcardCheckUtils.checkBankCard(bankCard)){
            ToastUtil.showToast(mActivity,"请输入正确的银行卡");
            return;
        }
        String s_province = mTvAddress.getText().toString().split("--")[0];
        String s_city = mTvAddress.getText().toString().split("--")[1];
        String s_county = mTvAddress.getText().toString().split("--")[2];
        Log.e("s_province",s_province);
        Log.e("s_city",s_city);
        Log.e("s_county",s_county);

        /*if (bankCard.length() < 19 || bankCard.length() > 19) {
            ToastUtil.showToast(mActivity, "请输入正确的银行卡号");
            return;
        }*/
        Map<String, String> map = new HashMap<>();
        if(s_county.equals("区")){
            ToastUtil.showToast(mActivity,"请选择开户地");
            return;
        }


        map.put("member_id", application.userId);
        map.put("branch", branch);

        map.put("bank_code", bankName);
        map.put("s_province", s_province);
        map.put("s_city", s_city);
        map.put("s_county", s_county);
        map.put("bank_code", bankId);


        map.put("bank_cardno", bankCard);
        application.apiService.bankSave(map)
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Subscriber<RetMap>() {
                    @Override
                    public void onCompleted() {

                    }
                    @Override
                    public void onError(Throwable e) {
                        Log.e(TAG, "onError: "+e.toString() );
                    }

                    @Override
                    public void onNext(RetMap retMap) {

                        if (retMap.status.equals("1")){
                            ToastUtil.showToast(mActivity,retMap.message);
                            finish();
                        }else{
                            ToastUtil.showToast(mActivity,retMap.message);
                            return;
                        }
                    }
                });
    }

    /**
     * 获取银行卡列表
     */
    private void getBankCard() {
        Map<String, String> map = new HashMap<>();
        map.put("member_id", application.userId);
        application.apiService.banklist(map)
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Subscriber<BankList>() {
                    @Override
                    public void onCompleted() {

                    }

                    @Override
                    public void onError(Throwable e) {

                    }

                    @Override
                    public void onNext(BankList bankList) {
                        bankOptionItems.addAll(bankList.list);


                    }
                });
    }


    @Override
    public int getLayoutId() {
        return R.layout.activity_bind_card_new;
    }

    @Override
    public Activity bindActivity() {
        return this;
    }


    @OnClick({R.id.ll_choose_bank, R.id.btn_submit})
    public void onClicked(View view) {
        switch (view.getId()) {
            case R.id.ll_choose_bank://选择银行卡按钮
                showBankView();

                break;



            case R.id.btn_submit://审核按钮
                bindCard();
                break;



        }
    }






    private void setListener() {
        mTvAddress.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                showPickerView();
            }
        });
    }

    private void showBankView() {

        OptionsPickerView pvOptions=new OptionsPickerView.Builder(this, new OptionsPickerView.OnOptionsSelectListener() {
            @Override
            public void onOptionsSelect(int options1, int options2, int options3, View v) {
                //返回的分别是三个级别的选中位置
                String text = bankOptionItems.get(options1).getPickerViewText() ;
                tvChooseBank.setText(text);
                bankId =   bankOptionItems.get(options1).bank_code;
            }
        }).setTitleText("")
                .setDividerColor(Color.GRAY)
                .setTextColorCenter(Color.GRAY)
                .setContentTextSize(13)
                .setOutSideCancelable(false)
                .build();
          /*pvOptions.setPicker(options1Items);//一级选择器
        pvOptions.setPicker(options1Items, options2Items);//二级选择器*/
        pvOptions.setPicker(bankOptionItems);//三级选择器


        pvOptions.show();
    }


    private void showPickerView() {
        OptionsPickerView pvOptions=new OptionsPickerView.Builder(this, new OptionsPickerView.OnOptionsSelectListener() {
            @Override
            public void onOptionsSelect(int options1, int options2, int options3, View v) {
                //返回的分别是三个级别的选中位置
                String text = options1Items.get(options1).getPickerViewText() +"--"+
                        options2Items.get(options1).get(options2) +"--"+
                        options3Items.get(options1).get(options2).get(options3);
                mTvAddress.setText(text);
            }
        }).setTitleText("")

                .setDividerColor(Color.GRAY)
                .setTextColorCenter(Color.GRAY)
                .setContentTextSize(13)
                .setOutSideCancelable(false)
                .build();
          /*pvOptions.setPicker(options1Items);//一级选择器
        pvOptions.setPicker(options1Items, options2Items);//二级选择器*/
        pvOptions.setPicker(options1Items, options2Items, options3Items);//三级选择器
        pvOptions.show();

    }

    private void initView() {
        mTvAddress = (TextView) findViewById(R.id.tv_address);
    }


    private void initJsonData() {   //解析数据

        /**
         * 注意：assets 目录下的Json文件仅供参考，实际使用可自行替换文件
         * 关键逻辑在于循环体
         *
         * */
        //  获取json数据
        String JsonData = JsonFileReader.getJson(this, "province_data.json");
        ArrayList<JsonBean> jsonBean = parseData(JsonData);//用Gson 转成实体

        /**
         * 添加省份数据
         *
         * 注意：如果是添加的JavaBean实体，则实体类需要实现 IPickerViewData 接口，
         * PickerView会通过getPickerViewText方法获取字符串显示出来。
         */
        options1Items = jsonBean;

        for (int i = 0; i < jsonBean.size(); i++) {//遍历省份
            ArrayList<String> CityList = new ArrayList<>();//该省的城市列表（第二级）
            ArrayList<ArrayList<String>> Province_AreaList = new ArrayList<>();//该省的所有地区列表（第三极）

            for (int c = 0; c < jsonBean.get(i).getCityList().size(); c++) {//遍历该省份的所有城市
                String CityName = jsonBean.get(i).getCityList().get(c).getName();
                CityList.add(CityName);//添加城市

                ArrayList<String> City_AreaList = new ArrayList<>();//该城市的所有地区列表

                //如果无地区数据，建议添加空字符串，防止数据为null 导致三个选项长度不匹配造成崩溃
                if (jsonBean.get(i).getCityList().get(c).getArea() == null
                        || jsonBean.get(i).getCityList().get(c).getArea().size() == 0) {
                    City_AreaList.add("");
                } else {

                    for (int d = 0; d < jsonBean.get(i).getCityList().get(c).getArea().size(); d++) {//该城市对应地区所有数据
                        String AreaName = jsonBean.get(i).getCityList().get(c).getArea().get(d);

                        City_AreaList.add(AreaName);//添加该城市所有地区数据
                    }
                }
                Province_AreaList.add(City_AreaList);//添加该省所有地区数据
            }

            /**
             * 添加城市数据
             */
            options2Items.add(CityList);

            /**
             * 添加地区数据
             */
            options3Items.add(Province_AreaList);
        }
    }

    public ArrayList<JsonBean> parseData(String result) {//Gson 解析
        ArrayList<JsonBean> detail = new ArrayList<>();
        try {
            JSONArray data = new JSONArray(result);
            Gson gson = new Gson();
            for (int i = 0; i < data.length(); i++) {
                JsonBean entity = gson.fromJson(data.optJSONObject(i).toString(), JsonBean.class);
                detail.add(entity);
            }
        } catch (Exception e) {
            e.printStackTrace();
            // mHandler.sendEmptyMessage(MSG_LOAD_FAILED);
        }
        return detail;
    }

}
